package com.osc.exam.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.osc.exam.base.StatusEnum;
import com.osc.exam.config.PageBean;
import com.osc.exam.constant.GlobalConstant;
import com.osc.exam.dao.ProgressDao;
import com.osc.exam.dao.StudentDao;
import com.osc.exam.entity.AdminResponse;
import com.osc.exam.entity.domain.Student;
import com.osc.exam.entity.vo.InterviewVO;
import com.osc.exam.entity.vo.StudentVO;
import com.osc.exam.error.AddStuException;
import com.osc.exam.error.CustomerException;
import com.osc.exam.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

@Service
@Slf4j
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDao studentDao;
    @Autowired
    private ProgressDao progressDao;

    /**
     * 学生信息录入功能
     *
     * @param studentVO
     * @return
     */
    @Override
    @Transactional(rollbackFor=Exception.class)
    public int insterData(StudentVO studentVO) {
        Set<String> cardId = new HashSet<>();
        cardId = studentDao.queryByCardId(studentVO.getCardId());
        log.info("录入学生的身份证号为："+cardId);
        if (!cardId.isEmpty()) {
            throw new AddStuException("该学生已添加");
        }
        log.info("传入的参数信息为"+studentVO);
        int num = studentDao.insertStudenVO(studentVO);
        return num;
    }

    /**
     * 学生进度查询
     *
     * @param status
     * @return
     */
    @Override
    public List<Student> selectAll(String status) {
        List<Student> studentList = studentDao.queryInterviewByLimit(status);
        return studentList;
    }


    /**
     * 删除学生信息
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor=Exception.class)
    public void deleteData(Integer id) {
        studentDao.deleteById(id);
    }

    /**
     * 添加面试评论信息
     *
     * @param interviewVO
     * @return
     */
    @Override
    @Transactional(rollbackFor=Exception.class)
    public int interviewResult(InterviewVO interviewVO) {
        // 大于等于及格通过本地面试
        log.info("传入的参数信息为："+interviewVO);
        if (interviewVO.getScore() >= StatusEnum.TWO.getStatus()) {
            int num = progressDao.insertinterviewResult(interviewVO);
            // 同时需要修改学生表中的学生状态
            // 当传入的参数为一面时，需要转换成学生表中对应的面试状态
            if (Objects.equals(interviewVO.getRound(), StatusEnum.ONE.getStatus())) {
                interviewVO.setRound(interviewVO.getRound() + StatusEnum.TWO.getStatus());
                studentDao.updateStuStatus(interviewVO.getStudentId(), interviewVO.getRound());
                return num;
            }
            // 当传入的参数为二面时，需要转换成学生表中对应的面试状态
            if (Objects.equals(interviewVO.getRound(), StatusEnum.TWO.getStatus())) {
                interviewVO.setRound(interviewVO.getRound() + StatusEnum.THREE.getStatus());
                studentDao.updateStuStatus(interviewVO.getStudentId(), interviewVO.getRound());
                return num;
            }
            interviewVO.setRound(interviewVO.getRound() + StatusEnum.FIVE.getStatus());
            studentDao.updateStuStatus(interviewVO.getStudentId(), interviewVO.getRound());
            return num;
        }
        // 当学生评价及格一下时
        int num = progressDao.insertinterviewResult(interviewVO);
        if (Objects.equals(interviewVO.getRound(), StatusEnum.ONE.getStatus())) {
            interviewVO.setRound(interviewVO.getRound() + StatusEnum.ONE.getStatus());
            studentDao.updateStuStatus(interviewVO.getStudentId(), interviewVO.getRound());
            return num;
        }
        if (Objects.equals(interviewVO.getRound(), StatusEnum.TWO.getStatus())) {
            interviewVO.setRound(interviewVO.getRound() + StatusEnum.TWO.getStatus());
            studentDao.updateStuStatus(interviewVO.getStudentId(), interviewVO.getRound());
            return num;
        }
        interviewVO.setRound(interviewVO.getRound() + StatusEnum.FOUR.getStatus());
        studentDao.updateStuStatus(interviewVO.getStudentId(), interviewVO.getRound());
        return num;
    }

    /**
     * 查询全部学生信息
     *
     *
     * @param cityApplied
     * @param positionApplied
     * @param name
     * @param status
     * @return
     */
    @Override
    public List<Student> queryAllByLimit(String cityApplied, String positionApplied, String name, String status) {
        List<Student> studentList = studentDao.queryAllDataByLimit(cityApplied, positionApplied,name.toUpperCase(), status);
        return studentList;
    }

    /**
     * 分页获取实习生列表
     * @return
     */
    @Override
    public List<Student> queryTraineeByPage() {
        List<Student> students =  studentDao.queryTraineeByPage();
        return students;
    }


    @Override
    public int getResume() {
        return studentDao.getResume();
    }


    @Override
    public boolean update(Student student) {
        student.setUpdateTime(new Date());
        return studentDao.update(student)>0;
    }


    @Override
    public boolean updateStatus(int id, int status,Date date) {
        return studentDao.updateStatus(id,status,date)>0;
    }


    @Override
    public List<Map<String, Object>> selectPartStu() {
        return studentDao.selectPartStu();
    }

    @Override
    public List<Map<String, Object>> getPost() {
        return studentDao.getPost();
    }

    /**
     * 文件上传功能
     * @param file
     */
    @Override
    @Transactional(rollbackFor=Exception.class)
    public void uploadFile(MultipartFile file) {
        File targetFile = new File("D:\\OSC_");
        try (FileOutputStream out = new FileOutputStream(targetFile + file.getOriginalFilename());){
            out.write(file.getBytes());
        } catch (Exception e) {
            throw new CustomerException("文件上传异常！");
        }
    }

    /**
     * 文件下载功能
     * @param fileName
     * @param response
     */
    @Override
    @Transactional(rollbackFor=Exception.class)
    public void download(String fileName, HttpServletResponse response) {
        String filePath = "D:\\" + fileName;
        File file = new File(filePath);
        if(file.exists()){
            response.setContentType("application/octet-stream");
            response.setHeader("content-type", "application/octet-stream");
            try {
                response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(file.getName(),"utf8"));
            } catch (UnsupportedEncodingException e) {

            }
            byte[] buffer = new byte[1024];
            //输出流
            OutputStream os = null;
            try(FileInputStream fis= new FileInputStream(file);
                BufferedInputStream bis = new BufferedInputStream(fis);) {
                os = response.getOutputStream();
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                throw new CustomerException("文件下载异常");
            }
        }
    }
}
